/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in Pw
*@des: ios poll
*@name: ios_pool.cpp
*@author: zhongsx
*@time: 2016-03-28
*********************************************************/

#include "ios_pool.h"

io_service_pool::io_service_pool(std::size_t pool_size) : next_io_service_(0)
{
	for (std::size_t i = 0; i < pool_size; ++i)
	{
		io_service_sptr io_service(new boost::asio::io_service());
		work_sptr work(new boost::asio::io_service::work(*io_service));
		io_services_.push_back(io_service);
		work_.push_back(work);
	}
}

void io_service_pool::start()
{
	for (std::size_t i = 0; i < io_services_.size(); ++i)
	{
		boost::shared_ptr<boost::thread> thread(new boost::thread(
			boost::bind(&boost::asio::io_service::run, io_services_[i])));
		threads_.push_back(thread);
	}
}

void io_service_pool::join()
{
	for (std::size_t i = 0; i < threads_.size(); ++i)
	{
		threads_[i]->join();
	}
}

void io_service_pool::stop()
{
	for (std::size_t i = 0; i < io_services_.size(); ++i)
	{
		io_services_[i]->stop();
	}
}

boost::asio::io_service& io_service_pool::get_io_service()
{
	boost::mutex::scoped_lock lock(mtx);
	boost::asio::io_service& io_service = *io_services_[next_io_service_];
	++next_io_service_;
	if (next_io_service_ == io_services_.size())
	{
		next_io_service_ = 0;
	}
	return io_service;
}
